<template>
    <div>
        <div class="contanier">
            <i @click="backTo"></i>
            <div class="box">
                <h1>登录</h1>
                <input type="text" placeholder="请输入账号" v-model="user.acc">
                <input type="password" placeholder="请输入密码" v-model="user.pwd">
                <div class="code">
                    <input type="text" placeholder="请输入验证码" v-model="user.captcha">
                    <canvas ref="canvas" @click="getVerify"></canvas>
                </div>
                <button @click="loginFn">登录</button>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { login, test } from '../api/request';
import { Toast } from 'vant';
import api from '../api/index';
import { Dialog } from 'vant';
import { useRouter } from 'vue-router';
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

const canvas = ref<HTMLElement>();
const w: number = 100;
const h: number = 40;
const host = api.url;

let pen: CanvasRenderingContext2D | null;
type U = {
    acc: string;
    pwd: string;
    captcha: string;
};

const user = ref<U>({
    acc: '',
    pwd: '',
    captcha: ''
});

const getVerify = () => {
    const img = new Image();
    img.src = `${host}/api/ver/captcha?${Math.random()}`;
    if (pen) {
        pen.clearRect(0, 0, w, h);
        img.onload = () => {
            pen.drawImage(img, 0, 0, w, h);
        };
    }
};

onMounted(() => {
    const ele = canvas.value;
    if (ele) {
        ele.width = w;
        ele.height = h;
        pen = ele.getContext('2d');
        if (pen) {
            getVerify(); // 获取验证码
        }
    }
});

const loginFn = async () => {
    const { acc, pwd, captcha } = user.value;

    if (!acc || !pwd || !captcha) {
        Toast('所有输入框不能为空');
        return; // 直接返回
    }

    try {
        // 验证验证码
        const content = await test({ captcha });
        if (content.code !== 200) {
            Toast('验证码错误');
            return;
        }

        // 如果验证码验证通过，继续登录
        const loginContent = await login({ account: acc, password: pwd });
        const { code,token } = loginContent;
        // console.log(loginContent)
        if (code === 200) {
            // 登录成功，存储 token
            localStorage.setItem("ACCOUNT",acc)
            console.log(localStorage.setItem("ACCOUNT",acc))
            localStorage.setItem("TOKEN",token)
            ElMessage({
                message: '登录成功',
                type: 'success',
                plain: true,
            });
            setTimeout(() => {
                $router.replace({ path: '/setting' });
            }, 150);
        } else {
            // 登录失败，提示用户注册
            Dialog.confirm({
                title: '提示',
                message: '该账号不存在，是否注册？',
            })
            .then(() => {
                setTimeout(() => {
                    $router.replace({ path: '/register' });
                }, 150);
            })
            .catch(() => {
                // 用户取消操作
                return;
            });
        }
    } catch (error) {
        console.error('登录过程中出错:', error);
        Toast('登录失败，请稍后再试');
    }
};

const $router = useRouter();
const backTo = () => {
    $router.go(-1);
};
</script>
<style scoped lang="scss">
@import '../common/scss/variable.scss';

.contanier {
    width: 90%;
    margin: 0 auto;
    margin-top: 40px;

    i {
        display: block;
        width: 13px;
        height: 12px;
        background-image: url(../assets/img/icon.png);
    }

    .box {
        width: 100%;
        height: 360px;
        margin: 120px auto 0;

        h1 {
            padding-top: 20px;
            font-size: 36px;
            text-align: center;
            margin-bottom: 20px;
        }

        input,
        button {
            width: 100%;
            height: 52px;
            margin-top: 10px;
            padding-left: 20px;
            box-sizing: border-box;
            border-radius: 10px;
        }

        .code {
            position: relative;

            input {
                position: relative;
                z-index: 1;
            }

            canvas {
                position: absolute;
                top: 16px;
                right: 10px;
                z-index: 22;
            }
        }

        button {
            background-color: $bgColor;
            border: 0;
            font-size: 13px;
            color: #fff;
        }
    }
}
</style>